<template>
  <div class="chat-wrapper">
    <div class="live-title">
      <span
        v-for="(item,index) in tabs"
        :key="index"
        class="title-item"
        :class="{active:isActive[index]}"
        @click="tabClick(index)"
      >{{item}}</span>
    </div>
    <div id="message-send-box-wrapper" v-show="this.tabSelected ===0">
      <!-- <liveLike /> -->

      <!-- 消息主体 -->
      <div class="message-list" ref="message-list" @scroll="this.onScroll">
        <div
          class="message-box"
          v-for="message in currentMessageList"
          :key="message.ID"
          :message="message"
        >
          <!-- 消息内容区分 -->

          <div class="position-right" v-if="message.flow==='out'">
            <div class="message-item" v-if="textMsg(message.type)">
              <!-- <div style="display: flex"> -->
              <div>
                <!-- <p class="message-nick">{{message.nick}}</p> -->
                <span class="message-date">{{getDate(message)}}</span>
              </div>
              <div class="message-container">
                <div class="triangle"></div>
                <template v-for="(item, index) in contentList(message.payload.text)">
                  <span
                    :key="index"
                    class="message-text"
                    v-if="item.name === 'text'"
                  >{{ item.text }}</span>
                  <img
                    v-else-if="item.name === 'img'"
                    :src="item.src"
                    width="20px"
                    height="20px"
                    :key="index"
                  />
                </template>
                <MessageStatusIcon v-if="message.status==='fail'" :message="message"></MessageStatusIcon>
              </div>
            </div>
            <img
              v-if="textMsg(message.type)"
              class="message-img"
              :src="message.avatar"
              @error="imgError(message)"
            />
          </div>

          <div class="position-left" v-else>
            <img
              v-if="textMsg(message.type)"
              class="message-img"
              :src="message.avatar"
              @error="imgError(message)"
            />
            <div class="message-item" v-if="textMsg(message.type)">
              <div style="display: flex">
                <p class="message-nick">{{message.nick}}</p>
                <span class="message-date">{{getDate(message)}}</span>
              </div>
              <div class="message-container">
                <div class="triangle"></div>
                <template v-for="(item, index) in contentList(message.payload.text)">
                  <span
                    :key="index"
                    class="message-text"
                    v-if="item.name === 'text'"
                  >{{ item.text }}</span>
                  <img
                    v-else-if="item.name === 'img'"
                    :src="item.src"
                    width="20px"
                    height="20px"
                    :key="index"
                  />
                </template>
                <MessageStatusIcon v-if="message.status==='fail'" :message="message"></MessageStatusIcon>
              </div>
            </div>
            <div class="tip-text" v-if="joinMsg(message.type)">
              <img class="tips-img" src="../../assets/image/guzhang.png" />
              <span>{{getGroupTipContent(message)}}</span>
            </div>
            <div class="tip-leave" v-if="leaveMsg(message.type)">
              <span>{{getGroupTipContent(message)}}</span>
            </div>
          </div>
        </div>
      </div>

      <div class="send-header-bar">
       <div class="emojisBox">
          <el-popover placement="top"  trigger="click">
          <div class="emojis">
            <div v-for="item in emojiName" class="emoji" :key="item" @click="chooseEmoji(item)">
              <img :src="emojiUrl + emojiMap[item]" style="width:30px;height:30px" />
            </div>
          </div>
          <i class="iconfont icon-smile" slot="reference" title="发表情"></i>
        </el-popover>
       </div>

        <div class="el-input">
          <el-input
            type="textarea"
            placeholder="发个弹幕呗~"
            v-model="messageContent"
            @focus="focus = true"
            @blur="focus = false"
            @keyup.enter.native="handleEnter"
            @keyup.ctrl.enter.prevent.exact="handleLine"
            class="input_text"
            style="width:100%; height:56px;"
          ></el-input>
        </div>

        <div class="send-btn">
          <el-button type="primary" @click="sendTextMessageto()" round>发送</el-button>
        </div>
      </div>
    </div>
    <div class="tab-summary" v-show="this.tabSelected ===1">
      <p>暂未开发</p>
    </div>
    <div class="tab-summary" v-show="this.tabSelected ===2">
      <p>暂未开发</p>
    </div>
  </div>
</template>

<script>
// import tim from "../../pages/chat/tim";
import TIM from "tim-js-sdk";
import tim from "../../tim";
// import COS from "cos-js-sdk-v5";
import { decodeText } from "../../utils/decodeText";
import { getFullDate } from "../../utils/date";
import { mapState } from "vuex";
import { Popover, Input } from "element-ui";
// import liveLike from "./liveLike/liveLike1.vue";
import MessageStatusIcon from "./message-status-icon.vue";
import { emojiMap, emojiName, emojiUrl } from "../../utils/emojiMap";

export default {
  //   name: "newChat",
  props: ["scrollMessageListToButtom"],
  components: {
    ElInput: Input,
    ElPopover: Popover,
    // liveLike: liveLike,
    MessageStatusIcon,
  },
  data() {
    return {
      isActive: [1, ""],
      tabs: ["聊天", "提问", "应用"],
      tabSelected: 0, //互动
      messageContent: "",
      isSendCustomMessage: false,
      sendCustomDialogVisible: false,
      surveyDialogVisible: false,
      form: {
        data: "",
        description: "",
        extension: "",
      },
      file: "",
      emojiMap: emojiMap,
      emojiName: emojiName,
      emojiUrl: emojiUrl,
      showAtGroupMember: false,
      atUserID: "",
      focus: false,
      groupId: "@TGS#3NLA6HUGV",
      nickName: "tantan",
      isMine: false,
      // currentMessageList: [],
      // showMessage: "",
    };
  },
  computed: {
    ...mapState({
      isSDKReady: (state) => state.user.isSDKReady,
      // isLogin: (state) => state.user.isLogin,
      userInfo: (state) => state.user.userInfo,
      chatInfo: (state) => state.conversation.chatInfo,
      currentMessageList: (state) => state.conversation.currentMessageList,
      userID: (state) => state.user.userID,
      // isMine:(state)=>state.conversation.isMine
    }),
    contentList() {
      // console.log(this.currentMessageList);
      return (text) => {
        return decodeText(text);
      };
    },
    getGroupTipContent() {
      return (message) => {
        return message.payload.text;
      };
    },
    getDate() {
      return (message) => {
        return getFullDate(new Date(message.time * 1000));
      };
    },

    //  isMine() {
    //     // console.log(this.currentUserProfile, this.currentConversation);
    //     return this.message.flow === 'out'
    //   },
  },
  updated() {
    this.keepMessageListOnButtom();
  },
  mounted() {
    // 开始登录
    this.getlogin();
  },
  methods: {
    getlogin() {
      // this.logout();
      let promise = tim.login({
        userID: "tanjie",
        userSig:
          "eJyrVgrxCdYrSy1SslIy0jNQ0gHzM1NS80oy0zLBwiWJeVmZqVCZ4pTsxIKCzBQlK0MTAwMgsjAzgsikVhRkFqUCxU1NTY0MDAwgoiWZuWAxSzNzAzMTY0uoKZnpQIMjyhPTjbyiXLMdKxMtC4sdjbINQsPLLEwNKn2N-UNyLZNyY-RLfC3zA0sji22VagGepTI4",
      });
      promise
        .then(function (imResponse) {
          console.log(imResponse.data); // 登录成功
          console.log("登录成功");
          // this.loading = false
          // this.$store.commit("toggleIsLogin", false);
          // this.$store.commit("startComputeCurrent");
          // this.$store.commit("showMessage", {
          //   type: "success",
          //   message: "登录成功",
          // });
          if (imResponse.data.repeatLogin === true) {
            // 标识账号已登录，本次登录操作为重复登录。v2.5.1 起支持
            console.log(imResponse.data.errorInfo);
          }
        })
        .catch(function (imError) {
          // this.$store.commit("showMessage", {
          //   message: "登录失败：" + message,
          //   type: "error",
          // });
          console.warn("login error:", imError); // 登录失败的相关信息
        });
    },

    //登出
    // logout() {
    //   let promise = tim.logout();
    //   promise
    //     .then(function (imResponse) {
    //       console.log(imResponse.data); // 登出成功
    //     })
    //     .catch(function (imError) {
    //       console.warn("logout error:", imError);
    //     });
    // },

    imgError(item) {
      item.avatar = require("../../assets/image/default.png");
    },
    tabClick(index) {
      // window.scroll(0, 0)    //切换tab，聊天区域滑到底部
      this.isActive = ["", ""];
      this.isActive[index] = 1;
      this.tabSelected = index;
    },
    // 如果滚到底部就保持在底部，否则提示是否要滚到底部
    keepMessageListOnButtom() {
      let messageListNode = this.$refs["message-list"];
      if (!messageListNode) {
        return;
      }
      // 距离底部20px内强制滚到底部,否则提示有新消息
      if (
        this.preScrollHeight -
          messageListNode.clientHeight -
          messageListNode.scrollTop <
        20
      ) {
        this.$nextTick(() => {
          messageListNode.scrollTop = messageListNode.scrollHeight + 60;
        });
        this.isShowScrollButtomTips = false;
      } else {
        this.isShowScrollButtomTips = true;
      }
      this.preScrollHeight = messageListNode.scrollHeight;
    },
    onScroll({ target: { scrollTop } }) {
      let messageListNode = this.$refs["message-list"];
      if (!messageListNode) {
        return;
      }
      if (
        this.preScrollHeight - messageListNode.clientHeight - scrollTop <
        20
      ) {
        // this.isShowScrollButtomTips = false
      }
    },
    reEditMessage(payload) {
      this.messageContent = payload;
    },
    handleLine() {
      this.messageContent += "\n";
    },
    handleEnter() {
      this.sendTextMessageto();
    },
    leaveMsg(type) {
      return type === "Live-Leave";
    },
    textMsg(type) {
      return type === "TIMTextElem";
    },
    joinMsg(type) {
      return type === "Live-Join";
    },
    // checkLogin() {
    //   this.messageContent = "";
    //   this.$store.commit("showMessage", {
    //     message: "请先登录",
    //     type: "warning",
    //   });
    //   this.$store.commit("toggleIsLogin", true);
    // },
    sendTextMessageto() {
      if (
        this.messageContent === "" ||
        this.messageContent.trim().length === 0
      ) {
        this.messageContent = "";
        return;
      }

      let message = tim.createTextMessage({
        to: "@TGS#3NLA6HUGV",
        conversationType: TIM.TYPES.CONV_GROUP,
        payload: {
          text: this.messageContent,
        },
        status: "unSend",
        time: Date.now() / 1000,
        nick: this.nickName,
        avatar: this.avatar,
        flow: "out",
      });
      this.$store.commit("pushCurrentMessageList", message);
      let promise = tim.sendMessage(message);
      console.log("22222");
      promise
        .then((imResponse) => {
          console.log("send success!!!");
          // 发送成功
          console.log(imResponse);
          console.log(imResponse.data.message.flow);
        })
        .catch((error) => {
          console.log("send  fail!!!");

          message.status = "fail";
          if (error.code === 80001) {
            error.message = "文本中可能包含敏感词汇";
          }
          this.$store.commit("showMessage", {
            type: "error",
            message: error.message,
          });
        });
      this.messageContent = "";
    },
    random(min, max) {
      return Math.floor(Math.random() * (max - min + 1) + min);
    },
    chooseEmoji(item) {
      this.messageContent += item;
    },
  },
};
</script>

<style lang="stylus" scoped>
.live-title {
  display: flex;
  justify-content: center;
  height: 26px;
  line-height: 26px;
  background-color: #fff;
  color: #333;
  text-align: center;
  margin: 0 auto;
  // border-bottom: 2px solid rgb(0, 0, 0, 0.8);
  font-size: 16px;
}

.active {
  border-bottom: 2px solid #f5a623;
  color: #f5a623;
}

.title-item {
  display: block;
  width: 50px;
  font-size: 12px;
  margin: 0 20px;
  /* border-bottom: 2px solid #f5a623 */
}

.summary-text {
  padding: 5px 15px;
  line-height: 25px;
  text-align: left;
  color: #ffffff;
}

#message-send-box-wrapper {
  /* height 100% */
  /* position relative */
  box-sizing: border-box;
  overflow: hidden;
  /* padding: 3px 20px 20px 20px */
}

.message-list {
  position: absolute;
  z-index: 1;
  width: 100%;
  top: 70px;
  bottom: 55px;
  overflow: auto;
  overflow-x: hidden;
  box-sizing: border-box;
  overflow-y: scroll;
  -webkit-overflow-scrolling: touch; // ios卡顿
  padding: 8px 20px;
  margin-bottom: 5px;
}

.emojis {
  width: 240px;
  padding: 10px 10px;
  height: 160px;
  box-sizing: border-box;
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  overflow-y: scroll;
  background-color: #fff;
}

.chat-wrapper {
  /* position: relative; */
  width: 20vw;
  height: 80vh;
  max-width: 240px;
  box-shadow: 0 11px 20px 0 rgba(0, 0, 0, 0.3);
  position: relative;

  .official-link {
    display: flex;
    text-decoration: none;
    color: #38c9ff;
    width: fit-content;
    float: right;
    height: 45px;
    align-items: center;
  }
}

.message-box {
  font-family: Microsoft YaHei, Arial, Helvetica, sans-serif, SimSun;
  color: #FFFFFF;
  width: 100%;
  // height: 60%;
  overflow: hidden;

  .position-right {
    display: flex;
    flex-direction: start;

    .message-img {
      display: inline-block;
      min-width: 40px;
      max-width: 40px;
      height: 40px;
      border-radius: 50%;
    }

    .message-item {
      flex: 1;
      font-size: 14px;
      padding: 4px 8px;
      text-align: right;
      line-height: 18px;
      word-wrap: break-word;
      white-space: normal;

    
      .message-nick, .message-date {
        font-size: 12px;
        line-height: 23px;
        color: #333;
      }

      .message-date {
        display: inline-block;
        margin-left: 5px;
      }

      .message-container {
        display: inline-block;
        position: relative;
        background-color: #fff;
        border-radius: 3px;
        border-top-left-radius: 0;
        padding: 8px 8px;

        .triangle {
          width: 0;
          height: 0;
          /* border-top:5px solid transparent; */
          border-top: 8px solid transparent;
          border-left: 8px solid #fff;
          position: absolute;
          right: -8px;
          bottom: 0;
        }
      }
    }

    .tip-text, .tip-leave {
      font-size: 14px;
      position: relative;
      line-height: 18px;
      word-wrap: break-word;
      white-space: normal;
      /* margin 0 auto */
      color: rgb(245, 166, 35); // #258ff3//#fea602

      .tips-img {
        display: inline-block;
        width: 20px;
        vertical-align: center;
      }
    }

    .tip-text {
      padding: 4px 35px;
    }

    .tip-leave {
      padding: 4px 40px;
    }

    .message-text {
      font-size: 14px;
      color: #333;
      background-color: #fff;
      white-space: normal;
      word-break: break-all;
      word-wrap: break-word;
    }
  }

  .position-left {
    display: flex;
    flex-direction: start;

    .message-img {
      display: inline-block;
      min-width: 40px;
      max-width: 40px;
      height: 40px;
      border-radius: 50%;
    }

    .message-item {
      flex: 1;
      font-size: 14px;
      padding: 4px 8px;
      position: relative;
      line-height: 18px;
      word-wrap: break-word;
      white-space: normal;
      width: 90%;
      margin-left: 6px;

      .message-nick, .message-date {
        font-size: 12px;
        line-height: 23px;
        color: rgba(254, 255, 254, 0.5);
      }

      .message-date {
        margin-left: 5px;
      }

      .message-container {
        display: inline-block;
        position: relative;
        background-color: #fff;
        border-radius: 3px;
        border-top-left-radius: 0;
        padding: 8px 8px;

        .triangle {
          width: 0;
          height: 0;
          /* border-top:5px solid transparent; */
          border-top: 8px solid transparent;
          border-left: 8px solid #fff;
          position: absolute;
          left: -8px;
          top: 0;
        }
      }
    }

    .tip-text, .tip-leave {
      font-size: 14px;
      position: relative;
      line-height: 18px;
      word-wrap: break-word;
      white-space: normal;
      /* margin 0 auto */
      color: rgb(245, 166, 35); // #258ff3//#fea602

      .tips-img {
        display: inline-block;
        width: 20px;
        vertical-align: center;
      }
    }

    .tip-text {
      padding: 4px 35px;
    }

    .tip-leave {
      padding: 4px 40px;
    }

    .message-text {
      font-size: 14px;
      color: #333;
      background-color: #fff;
      white-space: normal;
      word-break: break-all;
      word-wrap: break-word;
    }
  }
}

.emoji {
  height: 30px;
  width: 30px;
  box-sizing: border-box;
}

.send-header-bar {
  width: 240px;
  position: absolute;
  bottom: 0;
  right: 0;
  box-sizing: border-box;
  height: 20vh;
  z-index: 100;
}

.send-header-bar span {
  // display: flex;
  // justify-content: center;
  // align-items: center;
  // line-height: 24px;
}
.emojisBox{
  width: 240px;
  height 30px
  line-height 30px
  border-bottom:#ccc solid 1px
  border-top:#ccc solid 1px
}
.send-header-bar i {
  display inline-block
  margin 0 8px
  cursor: pointer; 
  font-size: 24px;
  color: rgb(59, 124, 218);
}

.send-header-bar i:hover {
  color: #FFFFFF;
}

.el-input {
  background-color: #fff;
  color: #adadc0;
  font-size: 12px;
  height: 56px;
}

/deep/textarea.el-textarea__inner {
  display: block;
  width: 240px;
  height: 56px;
  padding: 0;
  outline: 0;
  vertical-align: middle;
  border: none;
  resize: none;
  overflow: auto;
  font-family: inherit;
}




.send-btn {
  display: flex;
  padding: 0 0 0 12px;
  border-radius: 3px;
  position absolute
  bottom 0
  right 0
}

.el-button--primary /deep/ {
  background-color: rgb(59, 124, 218);
  border-color: rgb(245, 166, 35); // #F5A623
  padding: 10px 20px;
  color #ffffff
}

textarea {
  resize: none;
}
</style>
